package com.shopmall.service;

import com.shopmall.mapper.AdminMapper;

import com.shopmall.pojo.Admin;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

@Service
public class AdminUserServiceImpl implements UserDetailsService {

    @Autowired
    AdminMapper adminMapper;

/*
    @Override
    public UserDetails loadUserByUsername(String username) { // 重写loadUserByUsername 方法获得 userdetails  类型用户
        Admin admin = adminMapper.queryAdminByUsername(username);
        if (admin == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        // 用于添加用户的权限。只要把用户权限添加到authorities 就大功告成一半
        for (SysRole role : admin.getRole_list()) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return new org.springframework.security.core.userdetails.User(admin.getUsername(), admin.getPassword(), authorities);
    }
*/


    /**
     *  实现security认证实现的方法
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            Admin admin = adminMapper.queryAdminByUsername(username);
            if (admin == null) {
                throw new UsernameNotFoundException("用户名不存在");
            }
            //用户权限
            List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
            String[] roles ;
            if(admin.getRole()==0){
                roles= new String[]{"ROLE_ROOT", "ROLE_SYS", "ROLE_MALL"};
            }
            else if(admin.getRole()==1){
                roles= new String[]{"ROLE_SYS", "ROLE_MALL"};
            }
            else
                roles= new String[]{"ROLE_MALL"};
            for (String role : roles) {
                if (StringUtils.isNotBlank(role)) {
                    authorities.add(new SimpleGrantedAuthority(role.trim()));
                }
            }
            /*
            创建一个用于认证的用户对象并返回，包括：用户名、密码、角色
             */

            return new org.springframework.security.core.userdetails.User(admin.getUsername(), admin.getPassword(), authorities);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
